package fr.ssd.ci.keystore;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import fr.ssd.ci.Constants;

public class KeystoreLoader {
		
	public static KeyStore load(final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
		return load(Constants.DEFAULT_KEYSTORE_PATH, passphrase);
	}


	public static KeyStore load(final String keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

		File file = new File(Constants.DEFAULT_KEYSTORE_FILENAME);
		if (file.isFile() == false) {
			File dir = new File(keystore);
			file = new File(dir, Constants.DEFAULT_KEYSTORE_FILENAME);
			if (file.isFile() == false) {
				file = new File(dir, Constants.DEFAULT_KEYSTORE_FILENAME);
			}
		}
		
		System.out.println("Loading KeyStore " + file + "...");
		InputStream in = new FileInputStream(file);
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(in, passphrase);
		in.close();
		return ks;
	}

}